<template>
  <v-chart :key="key" :style="`width: ${chartWidth}; height: ${chartHeight};`" :option="chartOptions"></v-chart>
</template>
<script lang="ts" setup>
import vChart from 'vue-echarts'
// import { ref, computed, watch } from 'vue'
import * as echarts from 'echarts/core'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
} from 'echarts/components';
import { PieChart, PieSeriesOption } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout
]);

const props = defineProps({
  list: {
    type: Array,
    required: true,
    default: () => []
  },
  title: {
    type: String,
    required: true,
    default: ""
  },
  width: {
    type: String,
    required: true,
    default: "100%"
  },
  height: {
    type: String,
    required: true,
    default: "100%"
  }
})
const chartWidth = computed(() => {
  if (typeof props.width === 'number') {
    return props.width + 'px'
  } else {
    return props.width
  }
})
const chartHeight = computed(() => {
  if (typeof props.height === 'number') {
    return props.height + 'px'
  } else {
    return props.height
  }
})
let chartOptions = ref({
  title: {
    text: "",
    subtext: "",
    left: 'left'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    top: 'bottom'
  },
  series: [
    {
      type: 'pie',
      radius: '50%',
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})
let key = ref(0)


watch(() => props.list, (newVal, oldVal) => {
  nextTick(() => {
    if (!isEmpty(newVal)) {
      updateTitle(props.title)
      updateList(newVal)
    }
  })
}, {
  deep: true,
  immediate: true
});

watch(() => props.title, (newVal, oldVal) => {
  nextTick(() => {
    if (!isEmpty(newVal)) {
      updateTitle(newVal)
    }
  })
}, {
  deep: true,
  immediate: true
});
const updateTitle = (value) => {
  chartOptions.value.title.text = value
  key.value++
}

const updateList = (data) => {
  chartOptions.value.title.subtext = `${data[0]?.value} / ${data[1]?.value || 0}`
  chartOptions.value.series[0].data = [...data]
  key.value++
}

</script>
